package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    //查询所有菜单信息
    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    //分页查询所有菜单信息
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        List<Menu> menus = menuDao.selectByCondition(queryString);
        if (menus!=null) {
            for (Menu menu : menus) {
                setMenu(menu);
            }
            PageInfo<Menu> pageMenu = new PageInfo(menus);
            return new PageResult(pageMenu.getTotal(),pageMenu.getList());
        }
        return null;

    }

    //添加子级菜单
    @Override
    public void setMenu(Menu menu){
        List<Menu> childMenus=menuDao.getChildrenMenus(menu.getId());
        if(childMenus!=null&&childMenus.size()>0){
            menu.setChildren(childMenus);
            for (Menu childMenu : childMenus) {
                setMenu(childMenu);
            }
        }

    }

    //新增菜单
    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    //删除菜单cff
    @Override
    public Result deleteById(Integer id) {
        try {
            menuDao.deleteById(id);
            return new Result(true,"菜单删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"该菜单有角色关联，不能删除!");
        }
    }

    //编辑菜单
    @Override
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    //通过ID查找菜单
    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }
}
